package cn.exrick.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.exrick.common.exception.XmallException;
import cn.exrick.mapper.TbOrderItemMapper;
import cn.exrick.mapper.TbOrderMapper;
import cn.exrick.mapper.TbOrderShippingMapper;
import cn.exrick.pojo.TbItemSkuGoodCat;
import cn.exrick.pojo.TbItemSkuGoodCatAttr;
import cn.exrick.pojo.TbOrder;
import cn.exrick.pojo.TbOrderExample;
import cn.exrick.pojo.TbOrderItem;
import cn.exrick.pojo.TbOrderItemExample;
import cn.exrick.pojo.TbOrderShipping;
import cn.exrick.pojo.common.DataTablesResult;
import cn.exrick.pojo.dto.ItemDto;
import cn.exrick.pojo.dto.OrderDetail;
import cn.exrick.pojo.front.Order;
import cn.exrick.service.ItemService;
import cn.exrick.service.ItemSkuGoodCatAttrService;
import cn.exrick.service.OrderService;

/**
 * @author Exrickx
 */
@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	private TbOrderMapper tbOrderMapper;
	@Autowired
	private TbOrderItemMapper tbOrderItemMapper;
	@Autowired
	private TbOrderShippingMapper tbOrderShippingMapper;

	@Autowired
	private ItemService itemService;

	@Autowired
	private ItemSkuGoodCatAttrService itemSkuGoodCatAttrService;

	@Override
	public TbOrder getById(String id) {
		return tbOrderMapper.selectByPrimaryKey(id);
	}

	@Override
	public DataTablesResult getOrderList(int draw, int start, int length, String search, String orderCol,
			String orderDir) {

		DataTablesResult result = new DataTablesResult();
		// 分页
		PageHelper.startPage(start / length + 1, length);
		List<TbOrder> list = tbOrderMapper.selectByMulti("%" + search + "%", orderCol, orderDir);
		PageInfo<TbOrder> pageInfo = new PageInfo<>(list);

		result.setRecordsFiltered((int) pageInfo.getTotal());
		result.setRecordsTotal(Math.toIntExact(cancelOrder()));

		result.setDraw(draw);
		result.setData(list);
		return result;
	}

	@Override
	public OrderDetail getOrderDetail(String orderId) {

		OrderDetail orderDetail = new OrderDetail();
		TbOrder tbOrder = tbOrderMapper.selectByPrimaryKey(orderId);

		TbOrderItemExample example = new TbOrderItemExample();
		TbOrderItemExample.Criteria criteria = example.createCriteria();
		criteria.andOrderIdEqualTo(orderId);
		List<TbOrderItem> orderItemList = tbOrderItemMapper.selectByExample(example);
		for (TbOrderItem orderItem : orderItemList) {
			ItemDto itemDto = null;
			try {
				itemDto = itemService.getItemById(Long.parseLong(orderItem.getItemId()));
			} catch (Exception e) {

			}
			if (itemDto != null) {
				TbItemSkuGoodCatAttr itemSkuGoodCatAttr = null;
				try {
					itemSkuGoodCatAttr = itemSkuGoodCatAttrService.findByItemId(itemDto.getId());
				} catch (Exception e) {
					e.printStackTrace();
				}
				List<TbItemSkuGoodCat> itemSkuGoodCatList = itemSkuGoodCatAttrService
						.findOneTreeByAttrId(itemSkuGoodCatAttr.getId());
				String sku = "[";
				if (!CollectionUtils.isEmpty(itemSkuGoodCatList)) {
					for (TbItemSkuGoodCat itemSkuGoodCat : itemSkuGoodCatList) {
						sku += itemSkuGoodCat.getName() + ":" + itemSkuGoodCat.getAttr().getName() + "-";
					}
				}
				if (sku.endsWith("-")) {
					sku = sku.substring(0, sku.length() - 1);
				}
				sku += "]";
				orderItem.setSkuName(sku);
			}
		}
		TbOrderShipping tbOrderShipping = tbOrderShippingMapper.selectByPrimaryKey(orderId);

		orderDetail.setTbOrder(tbOrder);
		orderDetail.setTbOrderItem(orderItemList);
		orderDetail.setTbOrderShipping(tbOrderShipping);
		return orderDetail;
	}

	@Override
	public int deliver(String orderId, String shippingName, String shippingCode, BigDecimal postFee) {

		TbOrder o = tbOrderMapper.selectByPrimaryKey(orderId);
		if (o == null) {
			throw new XmallException("订单不存在");
		}
		if (StringUtils.isEmpty(shippingName) || StringUtils.isEmpty(shippingCode)) {
			throw new XmallException("参数不足");
		}
		if (o.getStatus() != Order.ORDER_STATUS_WAIT_MAIL) {
			throw new XmallException("当前订单状态不能发货");
		}
		o.setShippingName(shippingName);
		o.setShippingCode(shippingCode);
		o.setPostFee(postFee);
		o.setConsignTime(new Date());
		o.setUpdateTime(new Date());
		o.setStatus(Order.ORDER_STATUS_WAIT_RECE);
		tbOrderMapper.updateByPrimaryKey(o);
		return 1;
	}

	@Override
	public int remark(String orderId, String message) {

		TbOrder o = tbOrderMapper.selectByPrimaryKey(orderId);
		o.setBuyerMessage(message);
		o.setUpdateTime(new Date());
		tbOrderMapper.updateByPrimaryKey(o);
		return 1;
	}

	@Override
	public int cancelOrderByAdmin(String orderId) {

		TbOrder o = tbOrderMapper.selectByPrimaryKey(orderId);
		o.setCloseTime(new Date());
		o.setUpdateTime(new Date());
		// 之前忘记设置常量了 将就这样看吧 0、未付款，1、已付款，2、未发货，3、已发货，4、交易成功，5、交易关闭
		o.setStatus(5);
		tbOrderMapper.updateByPrimaryKey(o);
		return 1;
	}

	@Override
	public Long countOrder() {

		TbOrderExample example = new TbOrderExample();
		Long result = tbOrderMapper.countByExample(example);
		if (result == null) {
			throw new XmallException("统计订单数目失败");
		}
		return result;
	}

	@Override
	public int deleteOrder(String id) {

		if (tbOrderMapper.deleteByPrimaryKey(id) != 1) {
			throw new XmallException("删除订单数失败");
		}

		TbOrderItemExample example = new TbOrderItemExample();
		TbOrderItemExample.Criteria criteria = example.createCriteria();
		criteria.andOrderIdEqualTo(id);
		List<TbOrderItem> list = tbOrderItemMapper.selectByExample(example);
		for (TbOrderItem tbOrderItem : list) {
			if (tbOrderItemMapper.deleteByPrimaryKey(tbOrderItem.getId()) != 1) {
				throw new XmallException("删除订单商品失败");
			}
		}

		if (tbOrderShippingMapper.deleteByPrimaryKey(id) != 1) {
			throw new XmallException("删除物流失败");
		}
		return 1;
	}

	@Override
	public int cancelOrder() {

		TbOrderExample example = new TbOrderExample();
		List<TbOrder> list = tbOrderMapper.selectByExample(example);
		for (TbOrder tbOrder : list) {
			judgeOrder(tbOrder);
		}
		return 1;
	}

	@Override
	public int update(TbOrder order) {
		return tbOrderMapper.updateByPrimaryKey(order);
	}

	/**
	 * 判断订单是否超时未支付
	 */
	public String judgeOrder(TbOrder tbOrder) {

		String result = null;
		if (tbOrder.getStatus() == Order.ORDER_STATUS_WAIT_PAY) {
			// 判断是否已超1天
			long diff = System.currentTimeMillis() - tbOrder.getCreateTime().getTime();
			long days = diff / (1000 * 60 * 60 * 24);
			if (days >= 1) {
				// 设置失效
				tbOrder.setStatus(Order.ORDER_STATUS_CLOSE);
				tbOrder.setCloseTime(new Date());
				if (tbOrderMapper.updateByPrimaryKey(tbOrder) != 1) {
					throw new XmallException("设置订单关闭失败");
				}
			} else {
				// 返回到期时间
				long time = tbOrder.getCreateTime().getTime() + 1000 * 60 * 60 * 24;
				result = String.valueOf(time);
			}
		}
		return result;
	}
}
